package com.goldgov.kduck.config;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
//    @Autowired
//    UserAccountService userAccountService;

//    @Autowired
//    LoginHistoryService loginHistoryService;

    RequestCache requestCache = new HttpSessionRequestCache();
    @Autowired
    ServerProperties serverProperties;
    @Value("${security.contentTypeIsText:false}")
    private boolean  contentTypeIsText;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {

        String redirectUrl = "";
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null && StringUtils.isNotEmpty(savedRequest.getRedirectUrl())) {
            redirectUrl = savedRequest.getRedirectUrl();
        }

//        LoginHistory loginHistory = new LoginHistory();
//        loginHistory.setUsername(authentication.getName());
//        loginHistory.setIp(ClientIpUtil.getIpAddress(request));
//        loginHistory.setDevice(request.getHeader("User-Agent"));
//        loginHistory.setRecordStatus(1);
//        loginHistoryService.asyncCreate(loginHistory);

//        userAccountService.loginSuccess(authentication.getName());

        boolean isAjax = "XMLHttpRequest".equals(request
                .getHeader("X-Requested-With")) || "apiLogin".equals(request
                .getHeader("api-login"));
        if (isAjax) {
            //TODO 验证IE浏览器兼容
            if (contentTypeIsText&& request.getHeader("user-agent").indexOf("MSIE")>0) {
                response.setHeader("Content-Type", "text/plain;charset=UTF-8");
            }else {
                response.setHeader("Content-Type", "application/json;charset=UTF-8");
            }
            try {
                HashMap map = new HashMap<String,Object>();
                map.put("authenticated",authentication.isAuthenticated());
                ObjectMapper objectMapper = new ObjectMapper();
                JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(response.getOutputStream(),
                        JsonEncoding.UTF8);
                objectMapper.writeValue(jsonGenerator, map);
            } catch (Exception ex) {
                if (logger.isErrorEnabled()) {
                    logger.error("Could not write JSON:", ex);
                }
                throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
            }
        } else {
            //Call the parent method to manage the successful authentication
///            setDefaultTargetUrl("/");
            if (StringUtils.isNotEmpty(redirectUrl)) {
                super.onAuthenticationSuccess(request, response, authentication);
            } else {
//                setDefaultTargetUrl("/");

                super.onAuthenticationSuccess(request,response,authentication);
//                if (
//                        authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_USER"));
//                        ) {
//                    response.sendRedirect(serverProperties.getServlet().getContextPath()+"/user");
//                } else {
//                    response.sendRedirect("/management/user");
//                }
            }
        }

    }

}
